package com.jiang.daily.Q2536;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/11/15 18:11
 */
class Solution {
    // public int[][] rangeAddQueries(int n, int[][] queries) {
    //     int[][] matrix = new int[n][n];
    //     for (int i = 0; i < queries.length; i++) {
    //         for (int j = queries[i][0]; j <= queries[i][2]; j++) {
    //             for (int k = queries[i][1]; k <= queries[i][3]; k++) {
    //                 matrix[j][k] += 1;
    //             }
    //         }
    //     }
    //     return matrix;
    // }

    public int[][] rangeAddQueries(int n, int[][] queries) {
        int[][] diff = new int[n + 1][n + 1];
        for (int[] query: queries) {
            int r1 = query[0], c1 = query[1];
            int r2 = query[2], c2 = query[3];
            diff[r1][c1] += 1;
            diff[r1][c2 + 1] -= 1;
            diff[r2 + 1][c1] -= 1;
            diff[r2 + 1][c2 + 1] += 1;
        }

        int[][] matrix = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int x1 = i == 0 ? 0 : matrix[i - 1][j];
                int x2 = j == 0 ? 0 : matrix[i][j - 1];
                int x3 = (i == 0 || j == 0) ? 0 : matrix[i - 1][j - 1];
                matrix[i][j] = diff[i][j] + x1 + x2 - x3;
            }
        }
        return matrix;
    }
}
